<?php

require_once 'ActionFramework/start.php';

class ViewMatchingAction extends Action {
	
	// No fields required
	
	public function trigger($request) {
		
		$user = $_SESSION['user'];
		
		global $DB;
		
		$candidates = array();
		foreach ($DB->get_all_users() as $candidate) {
			// Is not a candidate if it is the user himself, if the candidate is invisible, or the candidate has rejected the user
			if ($candidate->user_id === $user->user_id || $candidate->invisible || in_array($user->user_id, $candidate->rejections)) {
				continue;
			}
			if ($this->can_candidate_learn($user, $candidate)) {
				$candidates[] = $candidate;
			}
		}
		
		$matches = array();
		foreach ($candidates as $candidate) {
			if ($this->can_user_learn($user, $candidate)) {
				$matches[] = $candidate;
			}
		}
		
		return new ViewMatchingView($matches);	
	}
	
	private function can_candidate_learn($user, $candidate) {
		foreach ($candidate->unknown_languages_and_levels as $language_level) {
			$tmp = implode(', ', $user->known_languages);
			if (in_array($language_level[0], $user->known_languages)) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * Returns whether the candidate knows a language the user wants to learn
	 * @param User $user
	 * @param User $candidate
	 */
	private function can_user_learn($user, $candidate) {
		foreach ($candidate->known_languages as $language) {
			foreach ($user->unknown_languages_and_levels as $unknown_language_and_level) {
				if ($language === $unknown_language_and_level[0]) {
					return true;
				}
			}
		}
		return false;
	}
	
}

?>